/**
 * @File name: modules/common.c
 * @Synopsis:
 * @Author: xing.dai@aliyun.com
 * @Version: 0.0.1
 * @Date: 2018-08-23 15:53
 */

#include <string.h>
#include "types.h"
#include <ctype.h>

/**
 * @Synopsis
 *
 * @Param str: need string. The last character is '\0'
 *
 * @Returns
 */
char *trim(char *str)
{
    int i = 0;
    int j = strlen(str) - 1;
    int len = 0;

    while (str[i] == ' ' || str[i] == '\0')
        i++;
    while (str[j] == ' ' || str[j] == '\0' || str[j] == '\r' || str[j] == '\n')
        j--;

    len = j - i + 1;
    if (len < strlen(str)) {
        for (j = 0; j < len; j++)
            str[j] = str[j + i];
        str[len] = '\0';
    }

    return str;
}

#if 0
int tolower(int c)
{
    if (c >= 'A' && c <= 'Z')
        return c + 'a' - 'A';
    else
        return c;
}
#endif
/**
 * @Synopsis
 *
 * @Param str
 *
 * @Returns
 */
uint32 hexstr2uint32(char *str)
{
    int i;
    uint32 hex = 0;

    if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
        i = 2;
    else
        i = 0;

    for (; ; i++) {
        if ((str[i] >= '0' && str[i] <= '9') ||
                (str[i] >= 'a' && str[i] <= 'z') ||
                (str[i] >= 'A' && str[i] <= 'Z'))
            if (tolower(str[i]) > '9')
                hex = 16 * hex + (10 + tolower(str[i]) - 'a');
            else
                hex = 16 * hex + (tolower(str[i]) - '0');
        else
            break;
    }
    return hex;
}

int ishexstr(char *str)
{
    int i;
    int len = strlen(str);

    if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
        i = 2;
    else
        i = 0;

    while (i < len) {
        if ((str[i] >= '0' && str[i] <= '9') ||
                (str[i] >= 'a' && str[i] <= 'f') ||
                (str[i] >= 'A' && str[i] <= 'F'))
            i++;
        else
            return -1;
    }
    return 0;
}


